// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    const { productId, name, price, basePrice, quantity, image, specifications, selectedSpec } = event
    
    // 参数验证
    if (!productId || !name || !price || !quantity || !image) {
      return {
        success: false,
        message: '参数不完整'
      }
    }
    
    // 直接使用openid作为用户标识
    const userOpenid = openid
    
    // 检查商品是否已存在于购物车中（相同商品和规格）
    const existingItem = await db.collection('cart').where({
      userId: userOpenid,
      productId: productId,
      specifications: specifications
    }).get()
    
    if (existingItem.data.length > 0) {
      // 如果商品已存在，更新数量
      const item = existingItem.data[0]
      const newQuantity = item.quantity + quantity
      
      await db.collection('cart').doc(item._id).update({
        data: {
          quantity: newQuantity,
          updateTime: new Date()
        }
      })
      
      return {
        success: true,
        message: '商品数量已更新',
        data: {
          itemId: item._id,
          quantity: newQuantity
        }
      }
    } else {
      // 如果商品不存在，添加新商品
      const result = await db.collection('cart').add({
        data: {
          userId: userOpenid,
          productId: productId,
          name: name,
          price: price,
          basePrice: basePrice || price,
          quantity: quantity,
          image: image,
          specifications: specifications || '',
          selectedSpec: selectedSpec || {},
          createTime: new Date(),
          updateTime: new Date()
        }
      })
      
      return {
        success: true,
        message: '已加入购物车',
        data: {
          itemId: result._id,
          quantity: quantity
        }
      }
    }
  } catch (error) {
    console.error('添加到购物车失败：', error)
    return {
      success: false,
      message: '添加到购物车失败',
      error: error.message
    }
  }
}